package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.ExitLoginSuccess;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.DataCleanManager;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AppVersionUpdate;
import com.weixin.paleituo.view.ItemMyView;
import com.weixin.paleituo.view.VersionUpdatePopuwindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 设置
 */
public class SetActivity extends BasePersonActivity {
    @BindView(R.id.itenmyview_about_us_activiyt_set)
    ItemMyView mItenmyviewAboutUsActiviytSet;
    @BindView(R.id.itenmyview_version_check_activiyt_set)
    ItemMyView mItenmyviewVersionCheckActiviytSet;
/*    @BindView(R.id.itenmyview_weichat_number_activiyt_set)
    ItemMyView mItenmyviewWeichatNumberActiviytSet;*/
    @BindView(R.id.itenmyview_clean_buffer_activiyt_set)
    ItemMyView mItenmyviewCleanBufferActiviytSet;
    @BindView(R.id.tv_exit_login_activity_set)
    TextView mTvExitLoginActivitySet;
    private View mContentView;
    private AlertView mAlertView;
    private Dialog mLoadingDialog;
    private AppVersionUpdate mAppVersionUpdate;

    @Override
    protected View getContentView(Context context) {

        mContentView = UIUtils.inflate(this, R.layout.activity_set);
        return mContentView;
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, SetActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initEvent() {
        super.initEvent();

    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("设置");

        if (BaseApplication.isLoginSuccess) {
            mTvExitLoginActivitySet.setVisibility(View.VISIBLE);
        } else {
            mTvExitLoginActivitySet.setVisibility(View.INVISIBLE);
        }
        mItenmyviewVersionCheckActiviytSet.setDetails(""+ UIUtils.getVerName(this));
        try {
            mItenmyviewCleanBufferActiviytSet.setDetails( DataCleanManager.getTotalCacheSize(this));
        } catch (Exception e) {

            mItenmyviewCleanBufferActiviytSet.setDetails( "0k");
        }

    }



    @OnClick(R.id.itenmyview_about_us_activiyt_set)
    public void onMItenmyviewAboutUsActiviytSetClicked() {
        startActivity(AboutUsActivity.call2AboutUsActivity(this));
    }

    @OnClick(R.id.itenmyview_version_check_activiyt_set)
    public void onMItenmyviewVersionCheckActiviytSetClicked(View view) {
        if (mAppVersionUpdate==null){
        mAppVersionUpdate = new AppVersionUpdate(this,view,lifecycleSubject);

        }
        mAppVersionUpdate.checkVersionUpdate(false);
    }
   /* @OnClick(R.id.itenmyview_weichat_number_activiyt_set)
    public void onMItenmyviewWeichatNumberActiviytSetClicked() {

    }*/

    @OnClick(R.id.itenmyview_clean_buffer_activiyt_set)
    public void onMItenmyviewCleanBufferActiviytSetClicked() {
        AlertView   alertView = new AlertView("提示", "确定清除缓存", null, null, new String[]{"取消", "确定"}, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position==1){
                    DataCleanManager.clearAllCache(SetActivity.this);
                    try {
                        mItenmyviewCleanBufferActiviytSet.setDetails( DataCleanManager.getTotalCacheSize(SetActivity.this));
                    } catch (Exception e) {

                        mItenmyviewCleanBufferActiviytSet.setDetails("0k");
                    }
                }

            }
        });
        alertView.show();



    }
    @OnClick(R.id.tv_exit_login_activity_set)
    public void onMTvExitLoginActivitySetClicked(final View view) {
        if (mAlertView == null) {
            mAlertView = new AlertView("提示", "确定退出登录吗?", null, null, new String[]{"取消", "确定"}, this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 1) {

                        if (!NetUtils.NetwrokIsUseful(SetActivity.this)){
                            ToastUtils.makeText(R.string.check_internet);
                            return;
                        }
                        Observable<StatusCode<String>> statusCodeObservable = ApiUtils.getApi().exitLogin(BaseApplication.sUserInfoBean.token, BaseApplication.sUserInfoBean.userId + "")
                                .compose(RxHelper.getObservaleTransformer())
                                .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (mLoadingDialog == null) {
                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(SetActivity.this, "");
                                }
                                LoadingDialogUtils.show(mLoadingDialog);

                            }
                        }).subscribeOn(AndroidSchedulers.mainThread());


                        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<String>(SetActivity.this) {

                            @Override
                            protected void _onNext(StatusCode<String> t) {
                                LoadingDialogUtils.closeDialog(mLoadingDialog);
                                String s = t.getData();

                                if (s!=null){

                                    BaseApplication.sUserInfoBean = null;
                                    BaseApplication.isLoginSuccess = false;
                                    PreferencesUtils.getInstance().putString(Contans.username,"");
                                    PreferencesUtils.getInstance().putString(Contans.password,"");
                                    EventBus.getDefault().post(new ExitLoginSuccess());

                                    MainActivity.goGoodsShop(SetActivity.this,4);


                                }else {
                                    ToastUtils.makeText(t.getDetailMsg()+"");
                                }
                            }

                            @Override
                            protected void _onError(String message) {
                                LoadingDialogUtils.closeDialog(mLoadingDialog);
                                LogUtils.e(TAG, "退出 登录 ：" + message.toString());
                                ToastUtils.makeText(message);



                            }
                        },"",lifecycleSubject,false,true);


                    }
                }
            });
        }
        mAlertView.show();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void exitLoginSuccess(ExitLoginSuccess exitLoginSuccess){
        mTvExitLoginActivitySet.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoadingDialogUtils.closeDialog(mLoadingDialog);
        EventBus.getDefault().unregister(this);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mAlertView != null && mAlertView.isShowing()) {
                mAlertView.dismiss();
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mAppVersionUpdate!=null){
            VersionUpdatePopuwindow popu = mAppVersionUpdate.getPopu();
            if (popu==null ||!popu.isShowing()){
                super.onBackPressed();
            }
        }else {
            super.onBackPressed();
        }

    }
}
